import { NextResponse } from "next/server";
import connect from "@/utils/mongodb";
import Post from "@/model/Post";
import { writeFile } from "fs/promises";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
import fs from "fs";

const __dirname = dirname(fileURLToPath(import.meta.url));

export const PUT = async (request, { params }) => {
  try {
    await connect();
    const { id } = await params; // 获取文章ID

    const contentType = request.headers.get("content-type");
    let postData = {};

    if (contentType?.includes("multipart/form-data")) {
      const formData = await request.formData();
      postData.title = formData.get("title");
      postData.desc = formData.get("desc");
      postData.content = formData.get("content");
      postData.username = formData.get("username");

      // 处理图片更新（如有新图片上传）
      const imageFile = formData.get("image");
      if (imageFile && imageFile.name) {
        const filename = `${Date.now()}-${imageFile.name.replace(/\s+/g, "-")}`;
        const imagePath = join(__dirname, "../../../../../public/uploads", filename);
        await fs.promises.mkdir(dirname(imagePath), { recursive: true });
        const buffer = Buffer.from(await imageFile.arrayBuffer());
        await writeFile(imagePath, buffer);
        postData.img = `/uploads/${filename}`; // 更新为新图片路径
      } else {
        // 无新图片上传，使用原有图片或URL
        postData.img = formData.get("imgUrl");
      }
    }

    // 查找并更新文章
    const updatedPost = await Post.findByIdAndUpdate(
      id,
      { $set: postData },
      { new: true } // 返回更新后的文档
    );

    if (!updatedPost) {
      return NextResponse.json(
        { message: "文章不存在" },
        { status: 404 }
      );
    }

    return NextResponse.json(updatedPost, { status: 200 });
  } catch (error) {
    console.error("更新文章错误:", error);
    return NextResponse.json(
      { message: "更新文章失败" },
      { status: 500 }
    );
  }
};

export const GET = async (request, { params }) => {
  const { id } = await params;

  try {
    await connect();

    const post = await Post.findById(id);

    return new NextResponse(JSON.stringify(post), { status: 200 });
  } catch (err) {
    return new NextResponse("Database Error", { status: 500 });
  }
};

export const DELETE = async (request, { params }) => {
  const { id } = await params;

  try {
    await connect();

    await Post.findByIdAndDelete(id);

    return new NextResponse("Post has been deleted", { status: 200 });
  } catch (err) {
    return new NextResponse("Database Error", { status: 500 });
  }
};
